package com.tbycoder.tby.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tbycoder.tby.entity.IposLogin;
import com.tbycoder.tby.entity.Request.LoginRequest;
import com.tbycoder.tby.entity.Request.ModifyRequest;
import com.tbycoder.tby.entity.Vo.LoginVo;
import com.tbycoder.tby.entity.enu.IndentityEnum;
import com.tbycoder.tby.excption.BizException;
import com.tbycoder.tby.mapper.IposLoginMapper;
import com.tbycoder.tby.service.IIposLoginService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tby
 * @since 2021-04-14
 */
@Service
public class IposLoginServiceImpl extends ServiceImpl<IposLoginMapper, IposLogin> implements IIposLoginService {

    @Resource
    IposLoginMapper iposLoginMapper;

    @Override
    public LoginVo login(LoginRequest loginRequest) {
        if(loginRequest.getPassword().equals("")&& loginRequest.getUserId().equals("")){
            return LoginVo.builder()
                    .identity(IndentityEnum.getIndentityById(IndentityEnum.VISITOR.getId()))
                    .name("")
                    .build();
        }
        IposLogin iposLogin = iposLoginMapper.selectOne(
                Wrappers.lambdaQuery(IposLogin.class).eq(IposLogin::getUserId,loginRequest.getUserId())
                        .eq(IposLogin::getPassword,loginRequest.getPassword())
        );
        LoginVo loginVo = null;
        String token = UUID.randomUUID().toString();
        if(iposLogin == null){
            throw new BizException("账号或密码错误");
        }else{
            iposLoginMapper.update(null,Wrappers.lambdaUpdate(IposLogin.class)
                    .eq(IposLogin::getUserId,loginRequest.getUserId())
            .set(IposLogin::getToken,token));
            loginVo = LoginVo.builder()
                    .identity(IndentityEnum.getIndentityById(iposLogin.getIdentityId()))
                    .name(iposLogin.getName())
                    .userId(iposLogin.getUserId())
                    .token(token)
                    .build();
        }
        return loginVo;
    }

    @Override
    public boolean modifyRequest(ModifyRequest modifyRequest) {
        IposLogin iposLogin = iposLoginMapper.selectOne(Wrappers.lambdaQuery(IposLogin.class)
                .eq(IposLogin::getUserId, modifyRequest.getUserId()));
        if(!iposLogin.getPassword().equals(modifyRequest.getPassword())){
            throw new BizException("原密码错误");
        }
        int update = iposLoginMapper.update(null, Wrappers.lambdaUpdate(IposLogin.class)
                .eq(IposLogin::getUserId, modifyRequest.getUserId())
                .set(IposLogin::getPassword, modifyRequest.getModifyPassword()));
        return true;
    }
}
